package com.doge.util.interceptor;

import com.doge.bean.pojo.admin.Admin;
import com.doge.bean.pojo.log.Log;
import com.doge.mapper.LogMapper;
import com.doge.util.auth.GetSubject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @program: doge
 * @description:
 * @author: Keyu Li
 * @create: 2021-12-01 14:08
 **/

@Component
public class LogInterceptor implements HandlerInterceptor {
    @Autowired
    LogMapper mapper;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if ("OPTIONS".equals(request.getMethod())) {
            return;
        }
        Log log = new Log();
        // 获取 管理员 和 ip
        Admin admin = GetSubject.getAdmin();
        log.setAdmin(admin.getUsername());
        log.setIp(GetSubject.getIp());
        log.setAddTime(new Date());
        log.setUpdateTime(new Date());
        log.setDeleted(false);
        log.setStatus(true); // 成功
        // 获取当前访问的url,判断对应的操作
        String op = request.getRequestURI().replace("/admin/", "");
        String action;
        String result;
        int type;
        if (op.startsWith("order")) {
            type = 2;   //是订单操作
            result = "订单编号：" + (String) request.getAttribute("orderSn");
            if (op.contains("ship")) {
                action = "发货";
            } else if (op.contains("delete")) {
                action = "删除订单";
                log.setStatus(false); // 删除永远是失败
            } else
                return;
        } else {
            type = 1;   //是安全操作
            result = "成功";
            String adminName = (String) request.getAttribute("adminName");
            if (op.contains("login")) {
                action = "登录";
            } else if (op.contains("logout")) {
                action = "退出";
            } else if (op.contains("admin/create")) {
                action = "新建管理员";
                result = "成功，操作对象：" + adminName;
            } else if (op.contains("admin/delete")) {
                action = "删除管理员";
                result = "成功，操作对象：" + adminName;
            } else if (op.contains("admin/update")) {
                action = "更新管理员";
                result = "成功，操作对象：" + adminName;
            } else
                return;
        }
        log.setType(type);
        log.setAction(action);
        log.setResult(result);
        // 记录操作
        mapper.insertSelective(log);
    }
}
